from __future__ import annotations

import typing as t

from tortoise.backends.base.client import BaseDBAsyncClient
from tortoise.models import Model as _Model


class Model(_Model):
    @classmethod
    def create_without_data(cls, auto_id, **kwargs) -> Model:
        """
        根据已有数据创建出一个数据库对象而不是直接查库，必须有auto_id，可以通过使用refresh_from_db获取数据库中最新的值
        """
        obj = cls()
        obj.auto_id = auto_id
        obj._saved_in_db = True

        not_valid_fields = set(kwargs.keys()) - set(cls._meta.db_fields)
        assert not not_valid_fields, AssertionError(
            f"{not_valid_fields} are not valid in {cls.__name__}"
        )

        for key in cls._meta.db_fields:
            if key in kwargs:
                setattr(cls, key, kwargs[key])
            else:
                setattr(cls, key, None)
        return obj

    async def refresh_from_db(
        self,
        fields: t.Optional[t.Iterable[str]] = None,
        using_db: t.Optional[BaseDBAsyncClient] = None,
    ) -> None:
        if not fields:
            fields = self._meta.db_fields
        return await super().refresh_from_db(fields, using_db)

    def to_dict(self) -> dict:
        obj_dict = {}
        for key, value in self.__dict__:
            if key in self._meta.db_fields:
                obj_dict[key] = value
        return obj_dict
